import 'dart:io';
import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainOrderModel.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

class CarOrderNewsPage extends StatefulWidget {
  final String orderID;

  CarOrderNewsPage(this.orderID, {Key key}) : super(key: key);

  @override
  _CarOrderNewsPageState createState() => _CarOrderNewsPageState();
}

class _CarOrderNewsPageState extends State<CarOrderNewsPage> {
  AmapController _controller;
  LatLng center01 = LatLng(39.90960, 116.397228);
  LatLng center02 = LatLng(39.90960, 116.397228);

  final otherText01 = TextEditingController();
  MainOrderNewsModel newsModel;
  DisOrderModel disOrderModel;
  bool isShow = false;
  bool isShowCode = false;
  int orderType;
  int remove = 0;
  int chooseRemove = 0;
  int daohangType = 0;
  String removeStr = "";
  String latStr = "";
  String lngStr = "";

  @override
  void initState() {
    super.initState();
    orderType = 0;
    uploadOrderData();
    getAddress();
  }

  void getAddress() async {
    PermissionStatus permissions = await Permission.locationWhenInUse.request();
    if (permissions.isGranted) {
      Location location = await AmapLocation.instance.fetchLocation();
      setData("city", location.city);
      setData("lat", location.latLng.latitude);
      setData("long", location.latLng.longitude);

      latStr = location.latLng.latitude.toString();
      lngStr = location.latLng.longitude.toString();
    } else {
      showToast('需要定位权限!');
    }
  }

  void uploadOrderData() {
    DioUtils.postHttp(
      context,
      "Usercommon/order_detail",
      parameters: {
        "token": getData("token"),
        "order_id": widget.orderID,
      },
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            setState(() {
              newsModel = MainOrderNewsModel.fromJson(t);
              orderType = newsModel.data.orderStatus;
              center01 = LatLng(
                double.parse(newsModel.data.sLat.toString()),
                double.parse(newsModel.data.sLng.toString()),
              );
              center02 = LatLng(
                double.parse(newsModel.data.rLat.toString()),
                double.parse(newsModel.data.rLng.toString()),
              );
              print("订单类型" + newsModel.data.orderStatus.toString());
              print("是否到付" + newsModel.data.isDeliveryPay.toString());
              addMarker();
            });
          }
        } else {
          showToast(model.msg);
        }
      },
      onError: (error) {
        showToast(error);
        print(error);
      },
    );
  }

  //显示发货 收货位置
  void addMarker() async {
    print("center01 == $center01");
    await _controller?.addMarkers([
      MarkerOption(
        coordinate: center01,
        infoWindowEnabled: false,
        anchorV: 1,
        iconProvider: AssetImage('images/MapFaImage.png'),
      ),
      MarkerOption(
        coordinate: center02,
        anchorV: 1,
        infoWindowEnabled: true,
        iconProvider: AssetImage('images/MapShouImage.png'),
      ),
    ]);
    await _controller?.addDriveRoute(
        from: center01, to: center02, lineWidth: 20);
    await _controller?.zoomToSpan([center01, center02]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(context, "订单详情"),
      body: Stack(
        children: <Widget>[
          // AmapView(
          //   zoomLevel: 15,
          //   rotateGestureEnabled: false,
          //   onMapCreated: (controller) async {
          //     _controller = controller;
          //     await AmapLocation.instance
          //         .init(iosKey: 'e5b94ea20faba1746723d30ad211574d');
          //     addMarker();
          //   },
          // ),
          // remove == 0 ? orderView() : removeView(),
          // daohangType == 1 ? daohangView() : Container(),
          Positioned(
              child: Column(
            children: [
              Expanded(
                child: AmapView(
                  zoomLevel: 16,
                  rotateGestureEnabled: false,
                  onMapCreated: (controller) async {
                    _controller = controller;
                    await AmapLocation.instance
                        .init(iosKey: 'e5b94ea20faba1746723d30ad211574d');
                    // addMarker();
                  },
                ),
              ),
              orderView(),
            ],
          )),
          remove == 0 ? Container() : removeView(),
          daohangType == 1 ? daohangView() : Container(),
        ],
      ),
    );
  }

  Widget orderNewsView() {
    return newsModel == null
        ? Container()
        : Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(6), topRight: Radius.circular(6)),
              // border: Border.all(color: Color(0xFF222222), width: 1),
              boxShadow: [
                BoxShadow(
                    color: Colors.black12,
                    offset: Offset(0.0, -1.0), //阴影xy轴偏移量
                    blurRadius: 15.0, //阴影模糊程度
                    spreadRadius: 1.0 //阴影扩散程度
                    )
              ],
            ),
            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(
                    left: setWidth(30),
                    right: setWidth(30),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        "订单详情",
                        style: TextStyle(
                          color: Color(0xFF333333),
                          fontSize: setFontSize(32),
                        ),
                      ),
                      IconButton(
                        icon: Image.asset(
                          !isShow
                              ? "images/OrderShowImage.png"
                              : "images/OrderHideImage.png",
                          width: setWidth(130),
                        ),
                        onPressed: () async {
                          print("object");
                          setState(() {
                            isShow = !isShow;
                          });
                          await _controller?.zoomToSpan([center01, center02]);
                        },
                      ),
                      InkWell(
                        child: Image.asset(
                          "images/ToOtherApp.png",
                          width: setWidth(130),
                        ),
                        onTap: () {
                          setState(() {
                            daohangType = 1;
                          });
                        },
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(
                    left: setWidth(30),
                    right: setWidth(30),
                  ),
                  child: Column(children: <Widget>[
                    addressView(
                      "发",
                      newsModel.data.orderStatus > 1
                          ? newsModel.data.sRealname
                          : "***",
                      newsModel.data.orderStatus > 1
                          ? newsModel.data.sMobile
                          : "${newsModel.data.sMobile.substring(0, 3)} **** ****",
                      newsModel.data.sAddress + newsModel.data.sBuildingNumber,
                    ),
                    SizedBox(height: setHeight(30)),
                    Container(
                      color: Color(0xFFE1E1E1),
                      height: 1,
                      padding: EdgeInsets.only(
                          left: setWidth(20), right: setWidth(20)),
                    ),
                    SizedBox(height: setHeight(30)),
                    addressView(
                      "收",
                      newsModel.data.orderStatus > 1
                          ? newsModel.data.rRealname
                          : "***",
                      newsModel.data.orderStatus > 1
                          ? newsModel.data.rMobile
                          : "${newsModel.data.rMobile.substring(0, 3)} **** ****",
                      newsModel.data.rAddress + newsModel.data.rBuildingNumber,
                    ),
                  ]),
                ),
                SizedBox(height: setHeight(30)),
                Container(
                  color: Color(0xFFE1E1E1),
                  height: 1,
                ),
                isShow ? otherView() : Container(),
                btnView()
              ],
            ),
          );
  }

  Widget daohangView() {
    return Positioned(
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        child: Container(
          color: Colors.black.withOpacity(.7),
          padding: EdgeInsets.only(
            top: screenHeight - appBarHeight - statusBarHeight - 300,
          ),
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(6)),
                border:
                    Border.all(color: Color(0xFF999999), width: setWidth(3))),
            child: Column(
              children: <Widget>[
                Container(
                  alignment: Alignment.centerRight,
                  child: InkWell(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(
                        setWidth(20),
                        setHeight(20),
                        setWidth(20),
                        setHeight(10),
                      ),
                      child: Image.asset(
                        "images/MainDismissImage.png",
                        width: setWidth(40),
                      ),
                    ),
                    onTap: () {
                      if (mounted) {
                        setState(() {
                          daohangType = 0;
                        });
                      }
                    },
                  ),
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.only(left: setWidth(30)),
                  child: Text(
                    "导航去哪里？",
                    style: TextStyle(
                      color: Color(0xFF333333),
                      fontSize: setFontSize(32),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                SizedBox(height: setHeight(110)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    InkWell(
                      child: Container(
                        decoration: BoxDecoration(
                            color: Color(0xFFFF7F27),
                            borderRadius: BorderRadius.all(Radius.circular(6)),
                            border:
                                Border.all(color: Color(0xFF333333), width: 2)),
                        child: Container(
                          padding: EdgeInsets.fromLTRB(
                            setWidth(30),
                            10,
                            setWidth(30),
                            10,
                          ),
                          child: Text(
                            "导航到起点",
                            style: TextStyle(
                              color: Color(0xFF333333),
                              fontSize: setFontSize(26),
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ),
                      ),
                      onTap: () {
                        print("object");
                        setState(() {
                          daohangType = 0;
                        });
                        gotoAMap(center01.longitude, center01.latitude);
                      },
                    ),
                    InkWell(
                      child: Container(
                        decoration: BoxDecoration(
                            color: Color(0xFFFF7F27),
                            borderRadius: BorderRadius.all(Radius.circular(6)),
                            border:
                                Border.all(color: Color(0xFF333333), width: 2)),
                        child: Container(
                          padding: EdgeInsets.fromLTRB(
                            setWidth(30),
                            10,
                            setWidth(30),
                            10,
                          ),
                          child: Text(
                            "导航到终点",
                            style: TextStyle(
                              color: Color(0xFF333333),
                              fontSize: setFontSize(26),
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ),
                      ),
                      onTap: () {
                        print("object");
                        setState(() {
                          daohangType = 0;
                        });
                        gotoAMap(center02.longitude, center02.latitude);
                      },
                    ),
                  ],
                )
              ],
            ),
          ),
        ));
  }

  Widget removeView() {
    return Positioned(
      left: 0.0,
      bottom: 0.0,
      right: 0.0,
      child: InkWell(
        onTap: () {
          removeFocus(context);
        },
        child: Container(
          padding: EdgeInsets.all(setWidth(30)),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(setWidth(20)),
              topRight: Radius.circular(setWidth(20)),
            ),
            // border: Border.all(color: Color(0xFF222222), width: 1),
            boxShadow: [
              BoxShadow(
                  color: Colors.black12,
                  offset: Offset(0.0, -1.0), //阴影xy轴偏移量
                  blurRadius: 15.0, //阴影模糊程度
                  spreadRadius: 1.0 //阴影扩散程度
                  )
            ],
          ),
          child: Column(
            children: dismissView(),
          ),
        ),
      ),
    );
  }

  List<Widget> dismissView() {
    List<Widget> dismissArr = [];
    for (var i = 0; i < disOrderModel.data.length + 3; i++) {
      if (i == 0) {
        dismissArr.add(
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                "确认放弃订单？",
                style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: setFontSize(36),
                ),
              ),
              InkWell(
                child: Image.asset(
                  "images/MainDismissImage.png",
                  width: setWidth(40),
                ),
                onTap: () {
                  setState(() {
                    remove = 0;
                  });
                },
              ),
            ],
          ),
        );
        dismissArr.add(
          SizedBox(height: setHeight(30)),
        );
      } else if (i == disOrderModel.data.length + 1) {
        dismissArr.add(
          Container(
            decoration: BoxDecoration(
                border: Border.all(color: Color(0xFFC9C9C9), width: 1)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(width: setWidth(30)),
                Column(children: <Widget>[
                  SizedBox(
                    height: setHeight(30),
                  ),
                  Text(
                    "其他：",
                    style: TextStyle(
                        fontSize: setFontSize(30), color: Colors.black),
                  )
                ]),
                Expanded(
                  child: TextField(
                    minLines: 1,
                    maxLines: 5,
                    controller: otherText01,
                    textAlign: TextAlign.start,
                    cursorColor: Colors.grey[400],
                    //设置光标
                    decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: "备注",
                        hintStyle: TextStyle(
                            fontSize: setFontSize(30),
                            color: Color(0xFFAEAEAE))),
                    style: TextStyle(
                        fontSize: setFontSize(30), color: Colors.black),
                    onTap: () {
                      setState(() {
                        removeStr = "";
                      });
                    },
                    onChanged: (value) {
                      removeStr = value;
                    },
                  ),
                )
              ],
            ),
          ),
        );
        dismissArr.add(
          SizedBox(height: setHeight(30)),
        );
      } else if (i == disOrderModel.data.length + 2) {
        dismissArr.add(
          Container(
              child: Row(
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Expanded(
                child: Text(
                  "放弃过多订单，会被禁止接单。",
                  style: TextStyle(
                    fontSize: setFontSize(26),
                    color: Color(0xFFFF7C4B),
                  ),
                ),
              ),
              InkWell(
                child: mainBtnView("确认放弃"),
                onTap: () {
                  print("object");
                  if (removeStr.length == 0) {
                    showToast("请选择或填写取消原因");
                    return;
                  }
                  showAlertDialog(context);
                },
              ),
            ],
          )),
        );
      } else {
        String disStr = disOrderModel.data[i - 1].content.toString();
        dismissArr.add(
          removeChooseView(disStr, disOrderModel.data[i - 1].id),
        );
        dismissArr.add(
          SizedBox(height: setHeight(20)),
        );
      }
    }
    return dismissArr;
  }

  Widget removeChooseView(String str, int index) {
    return InkWell(
      child: Container(
        padding: EdgeInsets.all(setWidth(30)),
        decoration: BoxDecoration(
            border: Border.all(color: Color(0xFFC9C9C9), width: 1)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              str,
              style: TextStyle(
                color: Color(0xFF333333),
                fontSize: setFontSize(28),
              ),
            ),
            Image.asset(
              removeStr == str
                  ? "images/MainSelectImage.png"
                  : "images/MainNoneImage.png",
              height: setHeight(40),
            )
          ],
        ),
      ),
      onTap: () {
        print("object");
        removeFocus(context);
        setState(() {
          removeStr = str;
        });
      },
    );
  }

  showAlertDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('你确定要放弃该订单吗?'),
          actions: <Widget>[
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
                print('取消');
              },
            ),
            FlatButton(
              child: Text('确定'),
              onPressed: () {
                dismissOrder();
              },
            )
          ],
        );
      },
    );
  }

  void dismissOrder() {
    DioUtils.postHttp(
      context,
      "Caruser/give_up_order",
      parameters: {
        "token": getData("token"),
        "order_id": widget.orderID,
        "concel_order_reson": removeStr,
      },
      onSuccess: (t) {
        print(t);
        if (t["code"].toString() == "1") {
          uploadOrderData();
          if (mounted) {
            setState(() {
              remove = 0;
              removeStr = "";
            });
          }
        } else {
          showToast(t["msg"].toString());
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  Widget orderView() {
    return Positioned(
      left: 10,
      right: 10,
      bottom: 0.0,
      child: newsModel == null
          ? Container()
          : Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(6), topRight: Radius.circular(6)),
                // border: Border.all(color: Color(0xFF222222), width: 1),
                boxShadow: [
                  BoxShadow(
                      color: Colors.black12,
                      offset: Offset(0.0, -1.0), //阴影xy轴偏移量
                      blurRadius: 15.0, //阴影模糊程度
                      spreadRadius: 1.0 //阴影扩散程度
                      )
                ],
              ),
              child: Column(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(
                      left: setWidth(30),
                      right: setWidth(30),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "订单详情",
                          style: TextStyle(
                            color: Color(0xFF333333),
                            fontSize: setFontSize(32),
                          ),
                        ),
                        IconButton(
                          icon: Image.asset(
                            !isShow
                                ? "images/OrderShowImage.png"
                                : "images/OrderHideImage.png",
                            width: setWidth(130),
                          ),
                          onPressed: () {
                            print("object");
                            setState(() {
                              isShow = !isShow;
                            });
                          },
                        ),
                        InkWell(
                          child: Image.asset(
                            "images/ToOtherApp.png",
                            width: setWidth(130),
                          ),
                          onTap: () {
                            setState(() {
                              daohangType = 1;
                            });
                            // if (newsModel.data.orderStatus > 1) {
                            //   setState(() {
                            //     daohangType = 1;
                            //   });
                            // } else {
                            //   showToast("接单后才能使用该功能");
                            // }
                          },
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(
                      left: setWidth(30),
                      right: setWidth(30),
                    ),
                    child: Column(children: <Widget>[
                      addressView(
                        "发",
                        newsModel.data.orderStatus > 1
                            ? newsModel.data.sRealname
                            : "***",
                        newsModel.data.orderStatus > 1
                            ? newsModel.data.sMobile
                            : "${newsModel.data.sMobile.substring(0, 3)} **** ****",
                        newsModel.data.sAddress +
                            newsModel.data.sBuildingNumber,
                      ),
                      SizedBox(height: setHeight(30)),
                      Container(
                        color: Color(0xFFE1E1E1),
                        height: 1,
                        padding: EdgeInsets.only(
                            left: setWidth(20), right: setWidth(20)),
                      ),
                      SizedBox(height: setHeight(30)),
                      addressView(
                        "收",
                        newsModel.data.orderStatus > 1
                            ? newsModel.data.rRealname
                            : "***",
                        newsModel.data.orderStatus > 1
                            ? newsModel.data.rMobile
                            : "${newsModel.data.rMobile.substring(0, 3)} **** ****",
                        newsModel.data.rAddress +
                            newsModel.data.rBuildingNumber,
                      ),
                    ]),
                  ),
                  SizedBox(height: setHeight(30)),
                  Container(
                    color: Color(0xFFE1E1E1),
                    height: 1,
                  ),
                  isShow ? otherView() : Container(),
                  btnView()
                ],
              ),
            ),
    );
  }

  Widget otherView() {
    return Column(
      children: <Widget>[
        SizedBox(height: setHeight(30)),
        Container(
          padding: EdgeInsets.only(
            left: setWidth(30),
            right: setWidth(30),
          ),
          child: Column(
            children: <Widget>[
              rowView("订单编号：", newsModel.data.orderNumber),
              rowView("发货时间：", newsModel.data.delivergoodstime),
              newsModel.data.orderStatus >= 2
                  ? rowView("接单时间：", newsModel.data.reciveOrderTime)
                  : Container(),
              newsModel.data.orderStatus == 3
                  ? rowView("取件时间：", newsModel.data.pickUpTime)
                  : Container(),
              newsStr().length != 0 ? rowView("货物信息：", newsStr()) : Container(),
              rowView("备        注：", newsModel.data.goodsRemark),
            ],
          ),
        ),
        Container(
          color: Color(0xFFE1E1E1),
          height: setHeight(20),
        ),
      ],
    );
  }

  Widget addressView(
    String typeStr,
    String name,
    String mobile,
    String address,
  ) {
    return Row(
      children: <Widget>[
        Text(
          "$typeStr:",
          style: TextStyle(color: Color(0xFF333333), fontSize: setFontSize(30)),
        ),
        SizedBox(width: setWidth(20)),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Text(
                    name,
                    style: TextStyle(
                      color: Color(0xFF333333),
                      fontSize: setFontSize(30),
                    ),
                  ),
                  InkWell(
                    child: Text(
                      newsModel.data.orderStatus < 2
                          ? mobile.substring(0, 3) +
                              "****" +
                              mobile.substring(mobile.length - 4, mobile.length)
                          : mobile,
                      style: TextStyle(
                        color: Color(0xFF267DFF),
                        fontSize: setFontSize(30),
                      ),
                    ),
                    onTap: () {
                      if (newsModel.data.orderStatus > 1) {
                        showCallDialog(context, mobile);
                      }
                      print(mobile);
                    },
                  )
                ],
              ),
              SizedBox(height: setHeight(10)),
              Text(
                address,
                style: TextStyle(
                    color: Color(0xFF666666), fontSize: setFontSize(24)),
              ),
            ],
          ),
        )
      ],
    );
  }

  showCallDialog(BuildContext context, String mobile) {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("确定要拨打$mobile 吗?"),
          // content: Text("确定要退出吗?"),
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          actions: [
            FlatButton(
              child: Text(
                "取消",
                style: TextStyle(
                  fontSize: setFontSize(30),
                ),
              ),
              onPressed: () {},
            ),
            FlatButton(
              child: Text(
                "确认",
                style: TextStyle(
                  color: Colors.orange,
                  fontSize: setFontSize(30),
                ),
              ),
              onPressed: () {
                launch("tel://$mobile");
              },
            ),
          ],
        );
      },
    );
  }

  Widget rowView(String typeStr, String content) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Text(
              typeStr,
              style: TextStyle(
                color: Color(0xFF333333),
                fontSize: setFontSize(30),
              ),
            ),
            Expanded(
              child: Text(
                content,
                style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: setFontSize(28),
                ),
              ),
            )
          ],
        ),
        SizedBox(height: setHeight(30)),
      ],
    );
  }

  String newsStr() {
    String shopnews = "";
    if (newsModel.data.csGoodsNumber != 0) {
      shopnews = shopnews +
          newsModel.data.csGoodsName +
          newsModel.data.csGoodsNumber.toString();
    }
    if (newsModel.data.bsGoodsNumber != 0) {
      shopnews = shopnews +
          " " +
          newsModel.data.bsGoodsName +
          newsModel.data.bsGoodsNumber.toString();
    }

    if (newsModel.data.otherGoodsName != null) {
      shopnews = shopnews + " " + newsModel.data.otherGoodsName;
    }

    return shopnews;
  }

  Widget btnView() {
    return Container(
      padding: EdgeInsets.fromLTRB(
        setWidth(20),
        setHeight(30),
        setWidth(20),
        setHeight(30),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            "共计:${newsModel.data.orderPrice}元",
            style: TextStyle(
              color: Colors.red,
              fontSize: setFontSize(34),
            ),
          ),
          Row(
            children: <Widget>[
              newsModel.data.orderStatus != 2
                  ? Container()
                  : InkWell(
                      child: mainBtnView(
                        "放弃订单",
                        lineColor: Color(0xFF999999),
                        backColor: Colors.white,
                      ),
                      onTap: () {
                        DioUtils.postHttp(
                          context,
                          "index/cancel_reason",
                          parameters: {"type": "2"},
                          onSuccess: (t) {
                            print(t);
                            MainModel model = MainModel.fromJson(t);
                            if (model.code == 1 && model.data != null) {
                              setState(() {
                                disOrderModel = DisOrderModel.fromJson(t);
                                remove = 1;
                              });
                            }
                          },
                          onError: (error) {
                            print(error);
                          },
                        );
                      },
                    ),
              SizedBox(width: setWidth(10)),
              InkWell(
                child: mainBtnView(btnStr()),
                onTap: () {
                  if (newsModel.data.orderStatus == 3) {
                    if (newsModel.data.isDeliveryPay != 1) {
                      DioUtils.postHttp(
                        context,
                        "Caruser/confirm_send",
                        parameters: {
                          "token": getData("token"),
                          "order_id": widget.orderID,
                        },
                        onSuccess: (t) {
                          print(t);
                          MainModel model = MainModel.fromJson(t);

                          if (model.code == 1) {
                            Navigator.pop(context);
                          }
                          // showToast(model.msg);

                          showEndImage(context);
                        },
                        onError: (error) {
                          print(error);
                        },
                      );
                    } else {
                      print("object");
                      showCodeImage(context);
                    }
                  } else {
                    showBtnDialog(context);
                  }
                },
              ),
            ],
          )
        ],
      ),
    );
  }

  String btnStr() {
    if (newsModel.data.orderStatus == 1) {
      return "确认接单";
    } else if (newsModel.data.orderStatus == 2) {
      return "确认取件";
    } else if (newsModel.data.orderStatus == 3) {
      return "确认送达";
    } else {
      return "已完成";
    }
  }

  String showStr() {
    if (newsModel.data.orderStatus == 1) {
      return "确认接单？";
    } else if (newsModel.data.orderStatus == 2) {
      return "确认取到货物，并确认货物完好？";
    } else if (newsModel.data.orderStatus == 3) {
      return "确定要进行此操作?";
    } else {
      return "确定要进行此操作?";
    }
  }

  showBtnDialog(BuildContext context) {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(showStr()),
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          actions: [
            FlatButton(
              child: Text(
                "取消",
                style: TextStyle(
                  fontSize: setFontSize(30),
                ),
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            FlatButton(
              child: Text(
                "确认",
                style: TextStyle(
                  color: Colors.orange,
                  fontSize: setFontSize(30),
                ),
              ),
              onPressed: () {
                Navigator.pop(context);
                if (latStr.length == 0 || lngStr.length == 0) {
                  getAddress();
                }
                switch (newsModel.data.orderStatus) {
                  case 1:
                    {
                      DioUtils.postHttp(
                        context,
                        "Caruser/revive_order",
                        parameters: {
                          "token": getData("token"),
                          "order_id": widget.orderID,
                          "c_lat": latStr,
                          "c_lng": lngStr,
                        },
                        onSuccess: (t) {
                          print(t);
                          MainModel model = MainModel.fromJson(t);
                          showToast(model.msg);
                          if (model.code == 1) {
                            uploadOrderData();
                          }
                        },
                        onError: (error) {
                          print(error);
                        },
                      );
                    }
                    break;
                  case 2:
                    {
                      DioUtils.postHttp(
                        context,
                        "Caruser/pickup_order",
                        parameters: {
                          "token": getData("token"),
                          "order_id": widget.orderID,
                        },
                        onSuccess: (t) {
                          print(t);
                          MainModel model = MainModel.fromJson(t);
                          showToast(model.msg);
                          if (model.code == 1) {
                            uploadOrderData();
                          }
                        },
                        onError: (error) {
                          print(error);
                        },
                      );
                    }
                    break;
                  case 3:
                    {}
                    break;
                  default:
                    {
                      Navigator.pop(context);
                    }
                }
              },
            ),
          ],
        );
      },
    );
  }

  void showCodeImage(BuildContext context) {
    showDialog(
      // 传入 context
      context: context,
      barrierDismissible: false,
      // 构建 Dialog 的视图
      builder: (BuildContext context) {
        return Container(
          alignment: Alignment.center,
          child: Container(
            width: setWidth(600),
            // height: setHeight(640),
            // color: Colors.white,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(6))),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.all(setHeight(16)),
                  decoration: BoxDecoration(
                      color: Color(0xFFEBEBEB),
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(6),
                          topRight: Radius.circular(6))),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "待付款",
                        style: TextStyle(
                          decoration: TextDecoration.none,
                          color: Color(0xFF4696FF),
                          fontSize: setFontSize(30),
                        ),
                      ),
                      GestureDetector(
                        child: Icon(Icons.close),
                        onTap: () {
                          Navigator.pop(context);
                          uploadOrderData();
                        },
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: setWidth(30)),
                  child: CachedNetworkImage(
                    imageUrl: newsModel.data.codeImage,
                    // height: setHeight(200),
                    // width: setHeight(200),
                    fit: BoxFit.cover,
                  ),
                ),
                Text(
                  "扫描二维码支付",
                  style: TextStyle(
                    decoration: TextDecoration.none,
                    color: Color(0xFF666666),
                    fontSize: setFontSize(30),
                  ),
                ),
                SizedBox(height: setHeight(20)),
                // FlatButton(
                //   onPressed: () {
                //     Navigator.pop(context);
                //     uploadOrderData();
                //   },
                //   child: mainBtnView("确定"),
                // ),
                // SizedBox(height: setHeight(6)),
              ],
            ),
          ),
        );
      },
    );
  }

  void showEndImage(BuildContext context) {
    showDialog(
      // 传入 context
      context: context,
      barrierDismissible: false,
      // 构建 Dialog 的视图
      builder: (BuildContext context) {
        return Container(
          alignment: Alignment.center,
          child: Container(
            width: setWidth(600),
            // height: setHeight(640),
            // color: Colors.white,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(6))),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.all(setHeight(16)),
                  decoration: BoxDecoration(
                      color: Color(0xFFEBEBEB),
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(6),
                          topRight: Radius.circular(6))),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "已完成",
                        style: TextStyle(
                          decoration: TextDecoration.none,
                          color: Color(0xFF4696FF),
                          fontSize: setFontSize(30),
                        ),
                      ),
                      GestureDetector(
                        child: Icon(Icons.close),
                        onTap: () {
                          Navigator.pop(context);
                          uploadOrderData();
                        },
                      ),
                    ],
                  ),
                ),
                Container(
                  height: 200,
                  padding: EdgeInsets.symmetric(horizontal: setWidth(30)),
                  child: Image.asset(
                    "images/MainOrderEndImage.png",
                    height: 100,
                    width: 100,
                    fit: BoxFit.fitWidth,
                  ),
                ),
                // Text(
                //   "已完成",
                //   style: TextStyle(
                //     decoration: TextDecoration.none,
                //     color: Color(0xFF4696FF),
                //     fontSize: setFontSize(30),
                //   ),
                // ),
                SizedBox(height: setHeight(20)),
              ],
            ),
          ),
        );
      },
    );
  }
}

/// 高德地图
Future<bool> gotoAMap(longitude, latitude) async {
  var url =
      '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';

  bool canLaunchUrl = await canLaunch(url);

  if (!canLaunchUrl) {
    showToast('未检测到高德地图~');
    return false;
  }

  await launch(url);

  return true;
}

/// 百度地图
Future<bool> gotoBaiduMap(longitude, latitude) async {
  var url =
      'baidumap://map/direction?destination=$latitude,$longitude&coord_type=bd09ll&mode=driving';

  bool canLaunchUrl = await canLaunch(url);

  if (!canLaunchUrl) {
    showToast('未检测到百度地图~');
    return false;
  }

  await launch(url);

  return canLaunchUrl;
}
